package net.yunxinyong.sign.service.impl;

import net.yunxinyong.sign.aop.CECException;
import net.yunxinyong.sign.entity.CecBase;
import net.yunxinyong.sign.entity.CecBaseExample;
import net.yunxinyong.sign.mapper.CecBaseMapper;
import net.yunxinyong.sign.service.CecBaseService;
import net.yunxinyong.sign.service.RecordService;
import net.yunxinyong.sign.utils.ListUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = CECException.class)
public class CecBaseServiceImpl implements CecBaseService {
    @Autowired
    private CecBaseMapper cecBaseMapper;
    @Autowired
    private RecordService recordService;

    @Override
    public CecBase select(int invid) {
        CecBaseExample cecBaseExample = new CecBaseExample();
        //id和企业状态为正常作为查询条件
        cecBaseExample.createCriteria().andInvIdEqualTo(invid).andStatusEqualTo(0);
        List<CecBase> list = cecBaseMapper.selectByExample(cecBaseExample);
        if (!ListUtils.isEmpty(list)) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public void update(CecBase cecBase, Integer adminId) {
        cecBase.setUpdateTime(new Date());
        int count = cecBaseMapper.updateByPrimaryKey(cecBase);
        boolean insert = recordService.insert(adminId, cecBase.getInvId(), null, 12);
        if (count <= 0 || !insert) {
            throw new CECException(501, "更新失败!");
        }
    }

    @Override
    public void insert(CecBase cecBase, Integer adminId) {
        cecBase.setUpdateTime(new Date());
        cecBase.setCreateTime(new Date());
        cecBase.setStatus(0);
        int count = cecBaseMapper.insert(cecBase);
        boolean insert = recordService.insert(adminId, cecBase.getInvId(), null, 12);
        if (count <= 0 || !insert) {
            throw new CECException(501, "添加失败!");
        }
    }
}
